package com.ssm.auth.common.context;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 登录上下文对象
 */
public class LoginContextHolder {
    /**
     * ThreadLocal不能在线程中进行传递；
     * InheritableThreadLocal可在线程间传递，但不能线程复用；
     * TransmittableThreadLocal用于解决线程池场景下ThreadLocal传递的问题的工具类(需要引入依赖)
     * 不止存放一个loginId，所以使用map作为泛型。
     */
    private static final InheritableThreadLocal<Map<String, Object>> THREAD_LOCAL = new InheritableThreadLocal<>();

    /**
     * set
     */
    public static void set(String key, Object value) {
        Map<String, Object> map = getThreadLocalMap();
        map.put(key, value);
        THREAD_LOCAL.set(map);
    }

    /**
     * get
     */
    public static Object get(String key) {
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    /**
     * remove
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * getLoginId
     */
    public static String getLoginId() {
        return (String) getThreadLocalMap().get("loginId");
    }

    /**
     * 当map有值，就复用map,防止每次set都把原有的map覆盖掉。
     */
    private static Map<String, Object> getThreadLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if(Objects.isNull(map)) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }
}
